from flask import g
from flask_restplus import Resource, Namespace, fields, marshal

from app.coupon.model import CouponCode
from app.user.decorators import token_required
from app.coin import dao
from common.responses import created, ok
from common.decorators import catch_error
from common.utils import custom_marshal_pagination
from common.request_parser import get_parser as base_get_parser

from common.constant import CoinUseAction
api = Namespace('coin', path='/coin')

# model
coin_record_model = api.model('coupon_model', {
    'id': fields.String(description='id'),
    'user_id': fields.Integer(description='操作者'),
    'action_name': fields.String(description='操作名称'),
    'coins_used': fields.Float(description='消耗积分数值'),
    'company_current_coins': fields.Float(description='当前剩余积分'),
})

# ---------- get parser ----------
get_parser = base_get_parser.copy()


class CoinRecordsResource(Resource):
    @catch_error
    @token_required
    @api.expect(get_parser)
    def get(self):
        args = get_parser.parse_args()
        coupon_pagination = dao.get_by_page(
            company_id=g.company_id,
            **args
        )
        # todo 改为重新获取
        coupon_pagination = custom_marshal_pagination(coupon_pagination)
        return ok(data=coupon_pagination, message='get coin records success')


class CoinRulesResource(Resource):
    @catch_error
    def get(self):
        return ok(data={
            'rules': [
                CoinUseAction.ADD_SPU, CoinUseAction.ADD_ORDER, CoinUseAction.ADD_CATEGORY
            ]
        }, message='get coin rules success')


# --------- route ----------
# 积分记录
api.add_resource(CoinRecordsResource, '/records')
# 积分规则
api.add_resource(CoinRulesResource, '/rules')
